package com.czp.infosharingplatformapp.controller;

import com.czp.infosharingplatformapp.dto.LoginRequest;
import com.czp.infosharingplatformapp.dto.UserResponse;
import com.czp.infosharingplatformapp.model.User;
import com.czp.infosharingplatformapp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

// 标注为 RestController, 用于处理 HTTP 请求
@RestController
@RequestMapping("/api/users") // 统一用户相关的路径
public class UserController {

    @Autowired
    private UserService userService; // 注入 UserService 服务

    // 用户注册
    @PostMapping("/register")
    public UserResponse registerUser(@RequestBody User user) {
        try {
            user.setRole("ROLE_USER"); // 默认角色设置为普通用户
            userService.register(user); // 调用 UserService 的注册逻辑
            return new UserResponse(200, "注册成功！", user);
        } catch (RuntimeException e) {
            return new UserResponse(400, "注册失败: " + e.getMessage(), null);
        }
    }

    // 用户登录
    @PostMapping("/login")
    public UserResponse login(@RequestBody LoginRequest loginRequest) {
        try {
            User user = userService.login(loginRequest.getUsername(), loginRequest.getPassword());
            return new UserResponse(200, "登录成功！欢迎：" + user.getUsername(), user);
        } catch (RuntimeException e) {
            return new UserResponse(401, "登录失败：" + e.getMessage(), null);
        }
    }

    @GetMapping("/all")
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }

    @DeleteMapping("/{id}")
    public String deleteUser(@PathVariable Long id) {
        return userService.deleteUser(id);
    }
}